# -*- coding:UTF-8 -*-

import commands
import sys
import time
from django.db.models import Q
from django.http import HttpResponse, request
from django.http import HttpResponseRedirect
from django.shortcuts import render,get_object_or_404, redirect
from django.views import generic

from .models import Record
from .forms import RecordForm
from django.contrib import messages
from django.contrib.auth import authenticate,get_user_model,login,logout
from .aform import UserLoginForm,UserRegisterForm
from django.views.decorators.csrf import csrf_protect

# Create your views here.


def jinge(request,id):
    if request.user.is_authenticated and request.user.is_staff:
       time1 = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
       result1 = [0,0]
       if id is "0":
            result1 = commands.getstatusoutput('sh /scripts/optest-env/core2ww_core.sh')
       elif id is "1":
            result1 = commands.getstatusoutput('sh /scripts/optest-env/core2real_core.sh')
       elif id is "2":
            result1 = commands.getstatusoutput('sh /scripts/python_app/test-loan2optest.sh')
       elif id is "3":
            result1 = commands.getstatusoutput('sh /scripts/python_app/test-loan2optest.sh')
       elif id is "4":
            result1 = commands.getstatusoutput('sh /scripts/python_app/test-loan2optest.sh')
       elif id is "5":
            result1 = commands.getstatusoutput('sh /scripts/python_app/test-loan2optest.sh')
       elif id is "6":
            result1 = commands.getstatusoutput('sh /scripts/python_app/test-loan2optest.sh')
       elif id is "7":
            result1 = commands.getstatusoutput('sh /scripts/python_app/test-loan2optest.sh')
       print (id)
       printr = result1[1]
       p1a = str(printr)
       p1b = p1a.decode('utf-8').encode('utf-8')
   # result1 = commands.getstatusoutput('sh /scripts/python_app/test-loan2optest.sh')
   # p2a = str(printr)
   # p2b = p1.decode('utf-8').encode('utf-8')
       context = {
        "title": "结果集",
        "time": time1,
        "result1": p1b
       }
       return render(request, "mine.html", context)
    return redirect('posts:mine')


def get_queryset(request):
    if request.user.is_authenticated and request.user.is_staff:
        query = request.GET.get('q')
        print(query)
        time1 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        context = {
            "title": "结果集",
            "time": time1,
            "result1": query
        }

        return render(request, "mine.html", context)
    return redirect('posts:mine')


class Search(generic.ListView):
    model = Record
    template_name = 'mine.html'

    def get_queryset(self):
        result = Record.objects.all()
        # result = super(Search, self).get_queryset()

        query = self.request.GET.get('q')
        a = "in"
        if query:
            result=result.filter(
                Q(patient__username__contains=query) |
                Q(flare_up_time__contains=query) |
                Q(symptoms__contains=query)|
                Q(symptoms_level__contains=query)|
                Q(activity_performed_during_onset_of_symptoms__contains=query)|

                Q(symptoms2__contains=query) |
                Q(symptoms_level2__contains=query) |
                Q(activity_performed_during_onset_of_symptoms2__contains=query)|

                Q(symptoms3__contains=query) |
                Q(symptoms_level3__contains=query) |
                Q(activity_performed_during_onset_of_symptoms3__contains=query) |

                Q(optional_description__contains=query)

                  )
            query_list = query.split()
        #     result = result.filter(
        #         reduce(operator.and_,
        #                (Q(title__icontains=q) for q in query_list)) |
        #         reduce(operator.and_,
        #                (Q(content__icontains=q) for q in query_list))
        #     )

        # return Album.objects.filter(driver__username__contains=query)
            return result
        return result


class Search1(generic.ListView):
    model = Record
    template_name = 'index.html'

    def get_queryset(self):
        result = Record.objects.all()
        # result = super(Search, self).get_queryset()

        query = self.request.GET.get('q')
        a = "in"
        if query:
            result=result.filter(
                Q(patient__username__contains=query) |
                Q(flare_up_time__contains=query) |
                Q(symptoms__contains=query)|
                Q(symptoms_level__contains=query)|
                Q(activity_performed_during_onset_of_symptoms__contains=query)|

                Q(symptoms2__contains=query) |
                Q(symptoms_level2__contains=query) |
                Q(activity_performed_during_onset_of_symptoms2__contains=query)|

                Q(symptoms3__contains=query) |
                Q(symptoms_level3__contains=query) |
                Q(activity_performed_during_onset_of_symptoms3__contains=query) |

                Q(optional_description__contains=query)

                  )
            query_list = query.split()
        #     result = result.filter(
        #         reduce(operator.and_,
        #                (Q(title__icontains=q) for q in query_list)) |
        #         reduce(operator.and_,
        #                (Q(content__icontains=q) for q in query_list))
        #     )

        # return Album.objects.filter(driver__username__contains=query)
            return result
        return result


def login_view(request):
    form = UserLoginForm(request.POST or None)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(username=username, password=password)
        login(request,user)
        return redirect('posts:mine')
    return render(request,"login_form.html",{"form":form})


def register_view(request):
    print(request.user.is_authenticated())
    title = "Register"
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleaned_data.get('password')
        user.set_password(password)
        user.save()
        new_user = authenticate(username=user.username,password=password)
        login(request,new_user)
        return redirect('posts:mine')
    context = {
        "form": form,
        "title":title
    }
    return render(request,"form1.html",context)


def logout_view(request):
    logout(request)
    return redirect('login')



def post_home(request):
    return HttpResponse("<h1>Hello</h1>")

def post_create(request):
    if request.user.is_authenticated():
        form = RecordForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.patient = request.user
            instance.save()
            messages.success(request,"Record saved")
            return redirect('posts:mine')

        # if request.POST == "POST":
        #     print request.POST.get("")
        context = {
            "form":form,
        }
        return render(request,"form.html",context)
    else:
        messages.error(request, "You are not admin, you can read but change nothing")
    return redirect('posts:mine')

def post_details(request,id):
    # instance = Record.object.get(id = 3)
    instance = get_object_or_404(Record,id=id)
    if request.user.is_authenticated():
        context = {
            "instance": instance,
            "title1": instance.id,
            "title2": instance.patient.username,
        }
    else:
        context = {
            "title": "Please login or register first"
        }
    return render(request, "details.html", context)

def post_mine(request):
    if request.user.is_authenticated():
        #queryset = Record.objects.all()
        context = {
            #"object_list":reversed(queryset),
            "title": "ZX 运维脚本"
        }
    else:
        context = {
            "title": "please login"
        }


    return render(request,"mine.html",context)


def post_list(request):
    if request.user.is_authenticated and request.user.is_staff:
        queryset = Record.objects.all()
        context = {
            "object_list":reversed(queryset),
            "title": "List"
        }
    else:
        messages.error(request,"You are not admin, you can read but change nothing")
        return redirect('posts:mine')

    return render(request,"index.html",context)

def post_update(request,id=None):
    instance = get_object_or_404(Record, id=id)
    if request.user.id == instance.patient.id:
        form = RecordForm(request.POST or None,instance=instance)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.patient = request.user
            instance.save()
            messages.success(request,"Record saved")
            return redirect('posts:mine')

        # if request.POST == "POST":
        #     print request.POST.get("")
        context = {
            "form": form,
        }
        return render(request, "form1.html", context)
    else:
        messages.error(request,"You are not admin, you can read but change nothing")
        return redirect('posts:mine')

def post_delete(request,id=None):
    instance = get_object_or_404(Record, id=id)
    if request.user.id == instance.patient.id:
        instance.delete()
        messages.success(request, "Record deleted")
    else:
        messages.error(request, "You are not admin, you can read but change nothing")
    return redirect('posts:mine')
